package com.igeek.d0618.test6;

import java.lang.reflect.Field;

/**
 * @Author: zhiyu
 * @Date:18:38
 * @DESC:
 */
public class PropertyDemo {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Student student = new Student(30,"张三");
        setProperty(student, "age", 25);
        System.out.println(student);

        Object obj = getProperty(student, "name");
        System.out.println(obj);
    }

    //写一个方法，此方法可将obj对象中名为propertyName的属性的值设置为value.
    public static void setProperty(Object obj, String propertyName, Object value) throws NoSuchFieldException, IllegalAccessException {
        Class<?> aClass = obj.getClass();
        Field field = aClass.getDeclaredField(propertyName);
        field.setAccessible(true);
        field.set(obj,value);
    }

    //写一个方法，此方法可以获取obj对象中名为propertyName的属性的值
    public static Object getProperty(Object obj, String propertyName) throws NoSuchFieldException, IllegalAccessException {
        Class<?> aClass = obj.getClass();
        Field field = aClass.getDeclaredField(propertyName);
        field.setAccessible(true);
        Object o = field.get(obj);
        return o;
    }
}
class Student {
    private int age;
    private String name;
    public Student() {

    }

    public Student(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student [age=" + age + ", name=" + name + "]";
    }
}
